import React, { memo, useState, useEffect } from 'react';
import { Form, Icon, message, Modal, Select, Empty } from 'antd';
import classNames from 'classnames';
import { isSuccess } from '@/utils/request';
import { hrOverviewRecheck } from '@/services/salaryManage/salaryCalculate';
import ItemChart from './itemChart';
import styles from './index.less';

const { querySalaryRecheckDataChartTypeList } = hrOverviewRecheck;

const { Option } = Select;

const Item = props => {
    const {
        year,
        month,
        employeeCode,
        diagramTypeCode,
        organizationCode,
        diagramTypeName = '',
        diagramTypSubOptionList = [],
        maxChooseNum = 1,
        showPopText = '',
        diagramEnType = 'line',
        querySalaryChartFn = querySalaryRecheckDataChartTypeList,
        applyStatus = 0,
        form
    } = props;

    const [chartList, setChartList] = useState([]);

    const [chooseList, setChooseList] = useState([]);

    const [loading, setLoading] = useState(false);

    const changeChartType = async (valArr = null, max = maxChooseNum) => {
        let list = [];
        if (!valArr) {
            list =
                diagramTypSubOptionList.length > max
                    ? diagramTypSubOptionList.slice(0, max).map(item => item.salaryItemId)
                    : diagramTypSubOptionList.slice().map(item => item.salaryItemId);
        } else {
            list = valArr;
        }
        setChooseList(list);
    };

    useEffect(() => {
        changeChartType();
    }, [year, month, employeeCode, organizationCode, diagramTypSubOptionList]);

    useEffect(() => {
        if (chooseList.length > 0) {
            setLoading(true);
            querySalaryChartFn({
                year,
                month,
                employeeCode,
                organizationCode,
                parentSalaryItemId: diagramTypeCode,
                applyStatus,
                salaryItemIds: chooseList
            })
                .then(res => {
                    if (isSuccess(res)) {
                        setChartList(res.data);
                    } else {
                        message.error(res.msg);
                    }
                })
                .finally(() => {
                    setLoading(false);
                });
        } else {
            setChartList([]);
        }
    }, [chooseList, year, month, employeeCode, diagramTypeCode, organizationCode]);

    const { getFieldDecorator, setFieldsValue, getFieldsValue } = form;

    //  弹窗=》确定按钮是否加载状态
    const [confirmLoad, setConfirmLoad] = useState(false);

    //  弹窗
    const [visible, setVisible] = useState(false);

    //  切换图表展示
    const okHandle = async () => {
        const { displayItems } = getFieldsValue();
        setConfirmLoad(true);
        await changeChartType(displayItems);
        setConfirmLoad(false);
        setVisible(false);
    };

    //  限制图表展示个数
    const changeValues = (rule, value, callback) => {
        let newArr;
        if (value.length > maxChooseNum) {
            newArr = [].concat(value.slice(0, maxChooseNum - 1), value.slice(-1));
            setFieldsValue({
                displayItems: newArr
            });
            callback(showPopText);
        } else {
            newArr = value;
            callback();
        }
    };

    return (
        <div className={styles.chartBox}>
            <i
                className={classNames('icon iconfont iconshezhi', styles.rightSetBtn)}
                onClick={() => setVisible(true)}
            />
            {chartList.length === 0 && !loading ? (
                <div style={{ height: 300, overflow: 'hidden' }}>
                    <Empty style={{ marginTop: 130 }} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                </div>
            ) : (
                <ItemChart chartData={chartList} chartType={diagramEnType} chartName={diagramTypeName} />
            )}

            <Modal
                title={`${diagramTypeName}显示设置`}
                visible={visible}
                onOk={okHandle}
                confirmLoading={confirmLoad}
                destroyOnClose
                onCancel={async () => {
                    setVisible(false);
                }}
            >
                <div className={styles.msg}>
                    <Icon type="exclamation-circle" theme="filled" />
                    {showPopText}
                </div>
                <Form layout="inline" className={styles.recheckForm} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }}>
                    <Form.Item label="显示项">
                        {getFieldDecorator('displayItems', {
                            initialValue: chooseList,
                            rules: [{ validator: changeValues }],
                            validateTrigger: 'onChange'
                        })(
                            <Select mode="multiple" style={{ width: '100%' }}>
                                {diagramTypSubOptionList.map(item => (
                                    <Option key={item.salaryItemId} value={item.salaryItemId}>
                                        {item.salaryItemName}
                                    </Option>
                                ))}
                            </Select>
                        )}
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default memo(Form.create()(Item));
